<!-- 权限管理-角色管理 -->
<template>
  <div class="app-container">

    <!-- 头部区域 -->
    <div class="search_and_new">
      <el-button type="primary" size="mini" @click="newRole">
        <i class="el-icon-plus el-icon--left" />
        添加角色
      </el-button>
    </div>
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      stripe
      :data="list"
      element-loading-text="Loading"
      :header-cell-style="{'text-align':'center'}"
      :cell-style="{'text-align':'center'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="角色名称" min-width="150">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="180">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" min-width="180">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否设置为注册用户默认角色" min-width="180">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.defaultRole" type="primary" size="mini" @click="default_roles(scope.row,true)">
            设为默认</el-button>
          <el-button v-else type="success" size="mini" style="margin-left:0;" @click="default_roles(scope.row,false)">
            取消默认</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="340">
        <template slot-scope="scope">
          <!-- <el-button type="primary" size="mini" @click="menu_power(scope.row,scope.$index)">菜单权限</el-button> -->
          <!-- <el-button type="primary" size="mini" @click="record_power(scope.$index)">数据权限</el-button> -->
          <el-button type="primary" size="mini" @click="operation(scope.row,scope.$index)">编辑</el-button>
          <el-button type="danger" size="mini" @click="operation_del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="paging_device">
      <el-pagination
        :current-page="pages.pageNumber"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pages.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pages.totalRows"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 弹出区域 -->
    <!-- 添加角色 -->
    <el-dialog :title="dialogTitle" :visible.sync="addRoles_dialog" :close-on-click-modal="false" width="30%">
      <el-form ref="notEmpty" :model="addRoles" label-position="right" label-width="80px">
        <el-form-item label="角色名称" prop="name" :rules="[{ required: true, message: '不能为空'}]">
          <el-input v-model="addRoles.name" size="mini" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addRoles.description" type="textarea" :rows="2" size="mini" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addRoles_cancel">取消</el-button>
        <el-button type="primary" size="mini" @click="addRoles_confirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="notEmpty" :model="edit" label-position="right" label-width="80px">
        <el-form-item label="角色名称" prop="name" :rules="[{ required: true, message: '不能为空'}]">
          <el-input v-model="edit.name" size="mini" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="edit.description" type="textarea" :rows="2" size="mini" />
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="edit.num" placeholder="请选择等级" style="width: 100%;">
            <el-option v-for="(item,index) in level" :label="item.label" :value="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSuccess">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 菜单权限 -->
    <el-dialog
      title="分配菜单权限"
      :visible.sync="menu_dialog"
      :close-on-click-modal="false"
      width="30%"
      :before-close="menu_cancel"
    >
      <el-tree
        ref="tree"
        :data="departments"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :check-strictly="true"
        :props="defaultProps"
        :default-checked-keys="getCheckedNode"
        @node-click="click_tree"
        @check-change="click_check()"
      />

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" style="border:0;" @click="menu_cancel">取消</el-button>
        <el-select v-model="open_data" size="mini" @change="openData">
          <el-option label="展开所有" value="1" />
          <el-option label="收合所有" value="2" />
          <el-option label="仅展开一级" value="3" />
          <el-option label="仅展开两级" value="4" />
        </el-select>
        <!-- <el-button size="mini" @click="choice">全选/反选</el-button> -->
        <el-button type="primary" size="mini" @click="menu_confirm">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      level: [{
        label: '无权限'
      },
      {
        label: '一级'
      },
      {
        label: '二级'
      },
      {
        label: '三级'
      },
      {
        label: '四级'
      },
      {
        label: '五级'
      },
      {
        label: '六级'
      }
      ],
      departments: [
        // 树状数据
      ],
      defaultProps: {
        // 树状类型
        children: 'children',
        label: 'title'
      },
      getCheckedNodes: [], // 所选的数组
      getCheckedNode: [], //  默认选中的节点 菜单权限
      // -----------------------------------------------------------
      list: [

      ],

      defaultProps2: {
        children: 'childrenDepartment',
        label: 'title'
      },
      record_data: [], // 数据权限树
      // 添加角色
      addRoles: {
        name: '',
        description: '',
        grade: '', // 等级
        id: ''
      },
      // 添加角色
      edit: {
        name: '',
        description: '',
        grade: '', // 等级
        id: '',
        num: null
      },
      // 添加角色 验证
      notEmpty: {
        name: ''
      },
      current_open: [], // 菜单权限 展开一级 两级
      current_data: [], // 菜单权限 全选/反选
      open_data: '1', // 菜单权限 展开绑定值
      addRoles_dialog: false, // 添加角色 弹框状态
      menu_dialog: false, // 菜单权限 弹窗状态
      record_dialog: false, // 数据权限 弹窗状态
      record_select: '0', // 数据权限 下拉绑定值
      listLoading: false, // 列表加载状态
      currentPage: 1, // 分页-当前页
      multipleSelection: [], // 表单选中的数据
      pages: {
        pageNumber: 1, // 当前页
        totalRows: 3, // 总条数
        pageSize: 10 // 每页条数
      },
      menus: [], // 存放全选id
      dialogCode: 1, // 为1代表是从新建进入的 为2代表是从编辑进入的
      dialogTitle: '添加角色',

      record_default: [], //  默认选中的节点 数据权限
      record_defaults: [], // 所选的数组 数据权限
      userId: '', // 当前所选id 暂存
      // / --------
      dialogVisible: false
    }
  },
  created() {
    this.pages.pagesNum = this.list.length
    this.role_getAllByPage()
    //  渲染菜单权限树
    this.$Http.hontPermissionGetAllList().then(res => {
      this.departments = res.result
    })
  },
  methods: {

    //       tree   权限树   测试方法 ---------------------------------------------------------
    closeTree() {

    },

    // 选中树状节点
    click_tree(item, e) {
      // 当参数为两个的时候，第一个是自身节点，第二个是父节点
      // console.log("选中的树状",item,e)

    },
    // 选中当前节点（对勾）
    click_check() {
      this.getCheckedNodes = []
      // console.log('数组',this.getCheckedNodes)
      // console.log( "选中的树状")
      this.$refs.tree.getCheckedNodes().forEach((item) => {
        this.getCheckedNode.push(item.id)
      })
    },
    // 菜单权限
    menu_power(data, index) {
      // console.log("// 菜单权限",data)
      this.menu_dialog = true
      this.getCheckedNode = []
      data.permissions.forEach((item, index) => {
        this.getCheckedNode.push(item.hontPermissionId)
      })
      console.log(this.getCheckedNode)
    },
    //     测试  方法------------------------------------------------------------
    // 角色管理   进入显示的列表
    role_getAllByPage() {
      const data = Object.assign({}, this.pages)
      this.$Http.getAllByPage(data).then(res => {
        if (res.code === 200) {
          this.pages.totalRows = res.result.totalElements
          this.list = res.result.content
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // tree 点击

    // tree2 点击
    click_check2() {
      this.record_defaults.length = 0 // 初始化所选的数组
      this.$refs.tree2.getCheckedNodes().forEach((item) => { // 将所有已选中的节点id push到数组里
        this.record_defaults.push(item.id)
        if (item.parentId != '0') {
          this.record_defaults.push(item.parentId)
        }
      })
      this.record_defaults = Array.from(new Set(this.record_defaults))
    },
    // 添加角色
    newRole() {
      this.dialogCode = 1
      this.dialogTitle = '添加角色'
      this.addRoles_dialog = true
    },
    // 添加/编辑角色 取消
    addRoles_cancel(notEmpty) {
      // this.addRoles = {}
      // this.resetForm(notEmpty)
      this.addRoles_dialog = false
      // this.role_getAllByPage()
    },
    // 添加/编辑角色 确认
    addRoles_confirm(notEmpty) {
      if (this.addRoles.name == '') {
        this.$message.error('请填写名称')
        return
      }
      if (this.addRoles.description == '') {
        this.$message.error('请填写备注')
        return
      }
      this.$Http.hontRoleSave({
        name: this.addRoles.name,
        description: this.addRoles.description
      }).then(res => {
        this.role_getAllByPage()
        this.addRoles_dialog = false
        this.$message.success('ok')
        this.addRoles.name = ''
        this.addRoles.description = ''
      })
    },
    // 编辑
    operation(data, index) {
      console.log(data)
      this.dialogVisible = true
      this.edit.name = data.name
      this.edit.description = data.description
      this.edit.id = data.id
      switch (data.level) {
        case 0:
          this.edit.grade = '无权限'
          this.edit.num = 0
          break
        case 1:
          this.edit.grade = '一级'
          this.edit.num = 1
          break
        case 2:
          this.edit.grade = '二级'
          this.edit.num = 2
          break
        case 3:
          this.edit.grade = '三级'
          this.edit.num = 3
          break
        case 4:
          this.edit.grade = '四级'
          this.edit.num = 4
          break
        case 5:
          this.edit.grade = '五级'
          this.edit.num = 5
          break
        case 6:
          this.edit.grade = '六级'
          this.edit.num = 6
          break
        default:
          ''
      }
    },
    // 编辑 x
    handleClose() {
      this.dialogVisible = false
    },
    //  编辑成功
    editSuccess() {
      // console.log(this.edit)
      this.$Http.hontPermissionEdit({
        name: this.edit.name,
        description: this.edit.description,
        level: this.edit.num,
        id: this.edit.id
      }).then(res => {
        this.role_getAllByPage()
        this.dialogVisible = false
        this.$message.success('编辑成功')
      })
    },
    // 删除
    operation_del(data) {
      const id = data.id
      this.$confirm('您确认要执行删除操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$Http.hontRoleDelAllByIds(id).then(res => {
            this.$message.success(res.message)
            this.role_getAllByPage()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除！'
          })
        })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 是否设置为注册用户默认角色
    default_roles(data, isshow) {
      this.$Http.hontRoleSetDefault({
        id: data.id,
        isDefault: isshow
      }).then(res => {
        // console.log(res)
        this.$message.success(res.message)
        this.role_getAllByPage()
      })
    },
    // 菜单权限 展开change
    getAllNodes(e) {
      console.log('菜单权限 展开change', e)
      for (const item of this.$refs.tree.store._getAllNodes()) {
        item.expanded = e // expanded = true时 树状全部展开
      }
    },
    // 菜单权限 展开change
    openData(e) {
      if (e == 1) {
        this.getAllNodes(true)
      } else if (e == 2) {
        this.getAllNodes(false)
      } else if (e == 3) {
        this.getAllNodes(false)
        this.current_open.length = 0
        this.menu_data.forEach(n => {
          this.current_open.push(n.id)
        })
      } else if (e == 4) {
        this.menu_data.forEach(m => {
          this.current_open.push(m.id)
          const howe = m.children.filter(function(e) {
            return e.children
          })
          howe.forEach(n => {
            this.current_open.push(n.id)
          })
        })
      }
    },
    // 菜单权限 全选/反选
    choice() {
      if (this.menus.length > 0) {
        this.$refs.tree.setCheckedKeys([])
        this.menus.length = 0
      } else {
        this.menu_data.forEach(m => {
          this.menus.push(m.id)
        })
        this.$refs.tree.setCheckedKeys(this.menus)
      }
    },
    // 菜单权限 提交
    menu_confirm(e) {
      this.$confirm('确认提交？')
        .then(_ => {
          const data = {
            roleId: this.userId,
            permIds: this.getCheckedNodes
          }
          this.$Http.role_editRolePerm(data).then(res => {
            this.role_getAllByPage()
            this.menu_dialog = false
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            this.role_getAllByPage()
          })
        })
        .catch(_ => {})
    },
    // 菜单权限 取消
    menu_cancel(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.menu_dialog = false
          this.role_getAllByPage()
        })
        .catch(_ => {})
    },

    // //     -------------------
    // 数据权限
    record_power(e) {
      this.record_dialog = true
      this.record_default.length = 0
      this.userId = this.list[e].id
      for (const x of this.list[e].permissions) {
        this.record_default.push(x.permissionId)
      }
    },
    // 数据权限 提交
    record_confirm() {
      this.$confirm('确认提交？')
        .then(_ => {
          const data = {
            roleId: this.userId,
            dataType: this.record_select
          }
          data.depIds = []
          if (data.dataType == '1') {
            data.depIds = this.record_defaults
          }
          this.$Http.role_editRoleDep(data).then(res => {
            this.record_dialog = false
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
          })
        })
        .catch(_ => {})
    },
    // 数据权限 取消
    record_cancel(e) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.record_dialog = false
        })
        .catch(_ => {})
    },
    // 数据权限 change
    recordData(e) {
      console.log(e)
    },
    // 表格选中状态
    handleSelectionChange(val) {
      this.multipleSelection = val
      // console.log(123154646,val)
    },
    // 每页条数
    handleSizeChange(val) {
      this.pages.pageSize = val
      this.role_getAllByPage()
    },
    // 当前页
    handleCurrentChange(val) {
      this.pages.pageNumber = val
      this.role_getAllByPage()
    }
  }
}
</script>
<style lang="scss" scoped>
  .app-container {
    padding: 0;
    margin: 20px;
  }

  .search_and_new {
    height: 5vh;

  }

  .paging_device {
    margin-top: 20px;
    text-align: center;
  }

  .el-select.el-select--mini {
    width: 80%;
  }

  .record_select {
    width: 100%;
    display: flex;

    span {
      display: inline-block;
      width: 20%;
      text-align: center;
      line-height: 28px;
      height: 28px;
    }

    .el-select.el-select--mini {
      width: 80%;
    }
  }
</style>
